<template>
    <view class="page-wrapper">
        <view class="content-box">
            <view class="label-text" style="margin-top: 10rpx;">{{ $t('pages.addDevice.wifiLink.WiFiNameLabel') }}</view>
            <CommonInput type="text" autocomplete="off" v-model="wifiForm.name" 
                :placeholder="$t('pages.addDevice.wifiLink.WiFiNamePlaceHolder')" maxlength="30">
            </CommonInput>
            <view class="label-text">{{ $t('pages.addDevice.wifiLink.WiFiPasswdLabel') }}</view>
            <CommonInput :type="showPasswd ? 'text' : 'password'" focus v-model="wifiForm.password"
                :placeholder="$t('pages.addDevice.wifiLink.WiFiPasswdPlaceHolder')" maxlength="30" autocomplete="off">
                <template #suffix>
                    <up-icon name="eye-off" v-if="showPasswd" size="24" @click="changePasswdStatus"></up-icon>
                    <up-icon name="eye" v-else size="24" @click="changePasswdStatus"></up-icon>
                </template>
            </CommonInput>

            <view class="bottom-box">
                <up-button :text="$t('common.next')" size="normal" type="primary" style="width: 620rpx;"
                    shape="circle" @click="submitForm"></up-button>
            </view>
        </view>
        <MyLoading ref="loadingRef" :title="`${countdown} ${$t('pages.addDevice.wifiLink.seconds')}`" :hasMask="true"></MyLoading>
    </view>
</template>

<script setup>
import CommonInput from '@/components/CommonInput/index.vue';
import MyLoading from '@/components/MyLoading/index.vue';
import { navigateToUniPage, CacheUtils, } from '@/utils/index.js';
import { ref, computed, reactive, onMounted, } from "vue";
import { onShow, } from "@dcloudio/uni-app";
import { addSheBeiApi, } from "@/api/request.js"
import { useI18n } from 'vue-i18n';


const { t } = useI18n();
const wifiForm = ref({
    name: '',
    password: '',
});
const loadingRef = ref(null)
const countdown = ref(0);
const timer = ref(null)
const showPasswd = ref(false);

const changePasswdStatus = () => showPasswd.value = !showPasswd.value;

const getConnectedWiFiNameOnAndriod = () => {
    //判断获取的WiFi是否为机型WiFi
    // 主窗体
    var MainActivity = plus.android.runtimeMainActivity()
    // 上下文  
    var Context = plus.android.importClass('android.content.Context')
    // 导入WIFI管理 和 WIFI 信息 的class  
    plus.android.importClass("android.net.wifi.WifiManager")
    plus.android.importClass("android.net.wifi.WifiInfo")
    plus.android.importClass("android.net.wifi.ScanResult")
    plus.android.importClass("java.util.ArrayList")
    // 获取 WIFI 管理实例  
    var wifiManager = MainActivity.getSystemService(Context.WIFI_SERVICE)

    // 获取当前连接WIFI的信息  
    var info = wifiManager.getConnectionInfo()

    // 获取当前 WIFI 连接的 SSID (WIFI 名称)  
    var ssid = info.getSSID()
    // 这里的 获取到的名称 是 带 双引号的 如 "cmcc"    
    // 所以我们这里处理一下  
    ssid = ssid.replace(/(^\"*)|(\"*$)/g, "")
    wifiForm.value.name = ssid

    var resultList = wifiManager.getScanResults(),
        len = resultList.size()

    for (var i = 0; i < len; i++) {

    }
}

const getConnectedWiFiNameOnIOS = () => {
    uni.startWifi({
        success: function () {
            return uni.getConnectedWifi({
                success: function (res) {
                    if (res.errMsg === 'getConnectedWifi:ok') {
                        // 获取到 Wi-Fi 信息
                        var ssid = res.wifi.SSID;
                        wifiForm.value.name = ssid;
                    } else {
                        console.error('获取 连接的Wi-Fi 信息失败:', res.errMsg);
                    }
                },
                fail: function (err) {
                    console.error('获取 Wi-Fi 信息失败:', err.errMsg);
                }
            });
        },
        fail: function (err) {
            console.error('初始化 Wi-Fi 模块失败', err);
        },
    })
}

const submitForm = () => {
    if (!wifiForm.value.name || !wifiForm.value.password) {
        uni.showToast({
            title: t('pages.addDevice.wifiLink.validateFail'),
            icon: "none"
        });
        return;
    }

    loadingRef.value.show()
    countdown.value = 30;
    timer.value = setInterval(() => {
        countdown.value -= 1;
        if (countdown.value <= 0) {
            countdown.value = 0
            loadingRef.value.hide()
            uni.$emit('wifiJieguo')
            clearInterval(timer.value);
            timer.value = null;
        }
    }, 1000);
    uni.$emit('blesendcmd', '', `:${wifiForm.value.name},${wifiForm.value.password},0`)
};

onShow(() => {
    uni.getNetworkType({
        success: function (res) {
            if (res.networkType != "wifi") {
                uni.showToast({
                    icon: 'none',
                    duration: 2000,
                    title: t('pages.addDevice.wifiLink.noConnectWifi'),
                })
            } else {
                uni.getSystemInfo({
                    success(res) {
                        if (res.osName == 'ios') {
                            getConnectedWiFiNameOnIOS();
                        } else {
                            getConnectedWiFiNameOnAndriod();
                        }
                    }
                })
            }
        }
    })
});

onMounted(() => {
    uni.$on('wifiResult', async () => {
        if (timer.value) {
            clearInterval(timer.value);
        }
        loadingRef.value.hide()
        let deviceInfo = uni.getStorageSync('shebeiInfo')
        let res = await addSheBeiApi(deviceInfo)
        if (res.response.result == true) {
            uni.showToast({
                title: t('common.operate_ok'),
                icon: 'none'
            })
            setTimeout(() => {
                uni.switchTab({
                    url: '/pages/index/index'
                })
            }, 500)
        } else {
            uni.showToast({
                title: res.response.msg,
                icon: 'none'
            })
        }
    })
	
})
</script>

<style lang="scss" scoped>
$bottom-height: 100rpx;

.page-wrapper {
    padding-bottom: $bottom-height;
}

.bottom-box {
    bottom: 0rpx;
    left: 0rpx;
    right: 0rpx;
    position: fixed;
    display: flex;
    justify-content: center;
    align-items: center;
    height: $bottom-height;
    box-sizing: border-box;
    background-color: #FFFFFF;
}

.content-box {
    height: 860rpx;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40rpx 30rpx;
    text-align: center;

}

.label-text{
    font-size: 28rpx;
    color: #4B5563;
    margin-bottom: 20rpx;
    margin-top: 50rpx;
    text-align: left;
    align-self: flex-start;
}

:deep(.common-input-wrapper){
    margin-right: 0;
    margin-left: 0;
    width: 100%;
    border-radius: 24rpx;
}
</style>